package coroutines

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

class RunTest() {

    @Test
    fun testWithTimeout() = runTest {
        assertFailsWith<TimeoutCancellationException> {
            withTimeout(1300L) {
                repeat(1000) { i ->
                    println("delay: $i times")
                    delay(500L)
                }
            }
        }

        val result = withTimeoutOrNull(1300L) {
            repeat(1000) { i ->
                println("delay: $i times")
                delay(500L)
            }
            "done"
        }
        println("result:$result")
    }


    @Test
    fun testWithContext() = runTest {
        val result = withContext(Dispatchers.Default) {
            delay(20)
            "done"
        }
        assertEquals("done", result)
    }
}